<?php

if (isset($_REQUEST['state'])) {
	$_overwrite_sid = $_REQUEST['state'];
}

require_once('includes/googleApi.php');
require_once('includes/provider-account.php');

echo 'originate session_id: ' . session_id();

if (isset($_REQUEST['code']))
{
	/* ok case */

	// save it
	$_SESSION['g_auth_code'] = $_REQUEST['code'];
	
	$json = cURLPost('https://accounts.google.com/o/oauth2/token', 
		array(
			'code' => $_REQUEST['code'],
			'client_id' => $google_app_client['id'],
			'client_secret' => $google_app_client['secret'],
			'redirect_uri' => $google_app_client['redirect_uri'],
			'grant_type' => 'authorization_code'
		), &$r, &$e);
	$val = json_decode($json);

	$_SESSION['g_access_token'] = $val->access_token;
	$_SESSION['g_token_type'] = $val->token_type;
	$_SESSION['g_expires_in'] = $val->expires_in;
	$_SESSION['g_id_token'] = $val->id_token;
	$_SESSION['g_refresh_token'] = $val->refresh_token;
	unset($_SESSION['me']);

	$p = new AccountProvider();
	
	// check by id_token first, no need to invoke java call.
	$r = $p->get(NULL, array(
			'id_token' => $val->id_token
		));
	

	if (empty($r)) {
		/* NOT FOUND - REGISTER */
		$result = TRUE;
		$err = NULL;
		$info = callGoogleApi('info', $_REQUEST, &$result, &$err);

		if ($result && isset($info['id']) && isset($info['name'])) {
			$login_id = $p->write($info['id'], array(
					'id_token' => $val->id_token,
					'screen_name' => $info['name']	
				));
		} else {
			$err = 'unexpected case, unable to retrieve GOOGLE USER INFO.';
			$result = FALSE;
			$login_id = 0;
		}
	} else {
		/* FOUND PULL uid */
		$r = array_keys($r);
		$login_id = $r[0];
	}
	echo '<pre>';
	$_SESSION['uid'] = $login_id;
	echo '$result ' . $result . '<br/>';
	echo '$login_id ' . $_SESSION['uid'] . '<br/>';
	echo '$err ' . $err . '<br/>';
	echo '$_REQUEST' . print_r($_REQUEST, TRUE);

}
elseif (isset($_REQUEST['error']))
{
	// error just close the screen.
	session_destroy ();
}
?>

<script type="text/javascript">
	window.close();
</script> 
